using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using ParserGenerator.Input;

namespace ParserGenerator.Exceptions
{
    [Serializable]
    public abstract class CompilationException : Exception
    {
        private List<SourceLocation> _locations;

        [NonSerialized]
        private ReadOnlyCollection<SourceLocation> _locationsWrapper;

        public ReadOnlyCollection<SourceLocation> Locations
        {
            get
            {
                if (_locationsWrapper == null)
                {
                    if (_locations == null)
                        _locations = new List<SourceLocation>();
                    _locationsWrapper = _locations.AsReadOnly();
                }
                return _locationsWrapper;
            }
        }

        protected CompilationException()
        {
        }

        protected CompilationException(string message)
            : base(message)
        {
        }

        protected CompilationException(string message, Exception inner)
            : base(message, inner)
        {
        }

        protected CompilationException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _locations = (List<SourceLocation>)info.GetValue(nameof(_locations), typeof(List<SourceLocation>));
        }

        public void AddLocation(SourceLocation location)
        {
            if (_locations == null)
                _locations = new List<SourceLocation>();
            _locations.Add(location);
        }

        public void AddLocation(SourceContext context)
        {
            if (context != null)
                AddLocation(context.Begin);
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(nameof(_locations), _locations, typeof(List<SourceLocation>));
            base.GetObjectData(info, context);
        }
    }
}
